package jacktgq.mazeSolver.solve;

import jacktgq.AlgoVisHelper;

import javax.swing.*;
import java.awt.*;

public class AlgoFrame extends JFrame{
    private MazeData mazeData;

    public AlgoFrame(String title, int width, int height, MazeData mazeData){

        super(title);
        this.mazeData = mazeData;

        AlgoCanvas canvas = new AlgoCanvas();
        setContentPane(canvas);

        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(width, height);
        setResizable(false);
        setLocationRelativeTo(null);
        setVisible(true);
    }

    public void render(MazeData mazeData) {
        this.mazeData = mazeData;
        repaint();
    }

    private class AlgoCanvas extends JPanel{

        public AlgoCanvas(){
            // 双缓存
            super(true);
        }

        @Override
        public void paintComponent(Graphics g) {
            super.paintComponent(g);
            int width = getWidth();
            int height = getHeight();

            Graphics2D g2d = (Graphics2D)g;
            // 抗锯齿
            RenderingHints hints = new RenderingHints(
                    RenderingHints.KEY_ANTIALIASING,
                    RenderingHints.VALUE_ANTIALIAS_ON);
            hints.put(RenderingHints.KEY_RENDERING, RenderingHints.VALUE_RENDER_QUALITY);
            g2d.addRenderingHints(hints);

            int m = mazeData.getM();
            int n = mazeData.getN();
            // 将游戏区域拆成M行N列个格子，如果是#就图上蓝色，否则不绘制
            // 每个小格子的宽度
            double gridWidth = width / n * 1.0;
            double gridHeight = height / m * 1.0;
            // 绘制迷宫
            char[][] maze = mazeData.getMaze();
            for (int i = 0; i < m; i++) {
                for (int j = 0; j < n; j++) {
                    if (maze[i][j] == MazeData.WALL) {
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.Cyan);
                    } else if (mazeData.path[i][j]) {
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.Amber);
                    } else {
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.White);
                    }

                    if(mazeData.result[i][j]) {
                        AlgoVisHelper.setColor(g2d, AlgoVisHelper.Red);
                    }
                    AlgoVisHelper.fillRectangle(g2d, j * gridHeight, i * gridWidth, gridWidth, gridHeight);
                }
            }
        }
    }
}


